package com.cqyc.shop.comm;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebFilter(urlPatterns="/*")
public class LoginFilter implements Filter{

	
	private String[]  ugions = new String[]{"showCart","payMent","accountSec","addr","comment","integral","order","userInfo","userOrder","joincart"};
	/**
	 * 获取要没登陆时需要过滤的页面
	 * @param url
	 * @return
	 */
	public boolean cotains(String url) {
		for(int i=0;i<ugions.length;i++) {
			if(url.contains(ugions[i])) {
				return true;
			}
		}
		return false;
	}
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response=(HttpServletResponse)resp;
		HttpSession session = request.getSession();
		Object user = session.getAttribute("user");
		String url = request.getRequestURI();
		if(user!=null) {
			chain.doFilter(request, response);
		}else {
			if(!cotains(url)) {
				chain.doFilter(request, response);
			}else {
				response.sendRedirect(request.getContextPath()+"/login_f.jsp");
			}
		}
	}

	@Override
	public void destroy() {
	}
	
}
